import classnames from 'classnames';
import React, { Children, useContext, FunctionComponentElement, useState, cloneElement, useRef } from 'react';
import Icon from '../Icon';
import { MenuContext } from './index';
import { MenuItemProps } from './menu-item';

export interface SubMenuProps {
    index?: string;
    title: string;
    className?: string;
    children?: React.ReactNode;
}

const SubMenu = (props: SubMenuProps) => {
    const { index, title, className, children } = props;
    const context = useContext(MenuContext);
    const timer = useRef<any>(null);
    const openedSubMenu = context.defaultOpenSubMenu as Array<string>;
    const isOpened = index && context.mode === 'vertical' ? openedSubMenu.includes(index) : false;
    const [menuOpen, setMenuOpen] = useState(isOpened);

    const classes = classnames('f-menu-submenu', className, {
        'f-is-active': context.index[0] === index,
        'f-is-opened': menuOpen
    });
    const handleClick = (e: React.MouseEvent) => {
        e.preventDefault();
        setMenuOpen(!menuOpen);
    };

    const handleMouse = (e: React.MouseEvent, toggle: boolean) => {
        if (timer.current) return;
        e.preventDefault();
        timer.current = setTimeout(() => {
            setMenuOpen(toggle);
            timer.current = null;
        }, 300);
    };
    const clickEvents = context.mode === 'vertical' ? {
        onClick: handleClick
    } : {};
    const hoverEvents = context.mode === 'horizontal' ? {
        onMouseEnter: (e: React.MouseEvent) => { handleMouse(e, true); },
        onMouseLeave: (e: React.MouseEvent) => { handleMouse(e, false); }
    } : {};
    const renderChildren = () => {
        const classes = classnames('f-submenu', {
            opened: menuOpen
        });
        const childrenComponent = Children.map(children, (child, i) => {
            const childElement = child as FunctionComponentElement<MenuItemProps>;

            if (childElement.type.displayName === 'MenuItem') {
                return cloneElement(childElement, { index: `${index}-${i}` });
            }
            console.error('SubMenu has MenuItem component');
        });

        return (
            <ul className={classes}>
                {childrenComponent}
            </ul>
        );
    };

    return (
        <li key={index} className={classes} {...hoverEvents}>
            <div className='f-submenu-title' {...clickEvents}>
                {title}
                <Icon icon="angle-down" className="arrow-icon" />
            </div>
            {renderChildren()}
        </li>
    );
};

SubMenu.displayName = 'SubMenu';
export default SubMenu;

// import Transition from '../Transition/index';
// <Transition
//     in={menuOpen}
//     timeout={300}
//     animation='zoom-in-top'
// >

// </Transition>